<?php
/**
 * @name 金币model
 */
namespace app\stream\model;
use app\common\model\OpenBase;

class Gift extends OpenBase {

	protected $tableName = 'user_data'; //user统计表
	//定义字段信息
	protected $fields = [
		0 => 'gold',
		1 => 'uid',
	];
	protected $exchange_list = []; //交换列表
	protected function _initialize() {
	}
	/**
	 * @name 添加金币
	 * @access public
	 * @param int $uid 用户UID--支出方
	 * @param int $num 添加的数量
	 * @param int $to_uid 接收方 0:表示系统
	 * @return boolean
	 */
	public function goldInc($uid = 0, $num = 0) {
		if (!$uid || !model('open/User')->hasUser((int) $uid)) {
			$this->error = '用户不存在';
			return false;
		}
		//不存在的时候创建
		if (!$this->where('uid=' . (int) $uid)->find()) {
			if (!$this->data(['uid' => $uid])->add()) {
				$this->error = '添加数据失败';
				return false;
			}
		}
		//重置副本储存
		$this->duplicate = [];
		if ($this->where('uid=' . (int) $uid)->setInc('gold', $num)) {
			return true;
		}
		$this->error = '添加数据失败';
		return false;
	}

	/**
	 * @name 扣除金币
	 * @param int $uid 用户UID
	 * @param int $num 减少的数量
	 * @return boolean or string 如果失败返回false,成功返回处理的单号
	 */
	public function goldDec($uid = 0, $num = 1) {
		if (!$uid || !model('open/User')->hasUser((int) $uid)) {
			$this->error = '用户不存在';
			return false;
		}
		$count = self::getGoldCountByUid($uid);
		if ($count <= 0 || $count < $num) {
			$this->error = '所剩金币不足';
			return false;
		}
		//扣除数量
		if ($this->where('uid=' . (int) $uid)->setDec('gold', $num)) {
			return true;
		}
		$this->error = '扣除金币失败';
		return false;
	}

	/**
	 * @name 获取指定用户的金币余额
	 * @access public
	 * @param int $uid 用户UID
	 * @return int 金币数
	 */
	public function getGoldCountByUid($uid = 0) {
		if ($uid) {
			$gold = $this->getFieldByUid($uid, 'gold');
		}
		return (int) $gold;
	}

	/**
	 * @name 添加Log
	 * @access public
	 * @param array $log 日志信息
	 * @param boolean $is_income 是否收入
	 * @return booean or int 成功返回记录的ID  失败返回false
	 */
	public function addLog($log = [], $is_income = true) {
		if ($is_income) {
			//收益记录
			$res = model('user/UserProfitLog')->addLog($log);
		} else {
			//消费记录
			$res = model('user/UserConsumeLog')->addLog($log);
		}
		return $res;
	}

	/**
	 * @name 获取列表数据
     * @param int $uid 指定用户的UID
     * @param int $limit 获取条数
     * @return array 数据列表
	 */
	public function getList($uid = 0, $limit = 10) {
	    if(!$uid) return [];
		$type = 'gold';
		//拼接查询sql;
		$sql = "SELECT t.desction,t.ctime,t.num,t.uid,t.to_uid,t.trade_order,t.order_type FROM (";
		$sql .= "SELECT desction,ctime,num,uid,to_uid,order_type,trade_order FROM __PREFIX__consume_log WHERE uid = " . $uid;
		$sql .= " AND type = '" . $type . "' UNION ALL ";
		$sql .= "SELECT desction,ctime,num,uid,to_uid,order_type,trade_order FROM __PREFIX__profit_log WHERE to_uid = " . $uid;
		$sql .= " AND type = '" . $type . "') t ORDER BY t.ctime DESC";
		$sql = strtr($sql, ['__PREFIX__' => C('database.prefix')]);
		$list = $this->findPageBySql($sql, null, $limit);
		if ($list['gtLastPage'] === true|!$list['data']) {
			return [];
		} else {
			foreach ($list['data'] as &$v) {
				/**if($v['num'] > 0){
				$v['desction'] = str_replace('[uname]',getUname($v['uid']),$v['desction']);
				}else{
				$v['desction'] = str_replace('[uname]',getUname($v['to_uid']),$v['desction']);
				}
				unset($v['uid'],$v['to_uid']);**/
				//是否为提现?
				if ($v['order_type'] == 3) {
					$v['save_status'] = (int) M('order')->getFieldByTradeOrder($v['trade_order'], 'save_status') ?: 2;
				} else {
					$v['save_status'] = 1;
				}
				$v['uname'] = getUname($v['uid']);
				$v['to_uname'] = getUname($v['to_uid']);
				$v['order_type'] = (int) $v['order_type'];
				$v['trade_order'] = jiami($v['trade_order']);
				unset($v['uid'], $v['to_uid']);
			}
			return $list['data'];
		}
	}
	/**
	 * @name 获取礼物赠送排行榜
     * @param int $uid 用户UID
     * @param int $limit 获取条数
     * @return 
	 */
	public function getGiftTopList($usid = 0, $limit = 10) {
	    $uid = model('open/User')->getUidByUsid($usid);
		if (!$uid) {
			return [];
		}

		$map['to_uid'] = $uid;
		$list = M('gift_count')->where($map)->field(['gold', 'uid'])->order('gold desc')->findPage($limit);
		if ($list['gtLastPage'] === true|!$list['data']) {
			return [];
		}
        $res = [];
        $userModel = model('open/User');
        foreach($list['data'] as $k=>$v){
            $res[$k]['user']['usid'] = $userModel->getUsidByUid($v['uid']);
            $res[$k]['user']['gold'] = (int)$v['gold'];
        }
		return $res;
	}
	/**
	 * @name 获取礼物赠送排行榜
     * @param int $uid 用户UID
     * @param int $limit 获取条数
     * @return 
	 */
	public function getPresenterTopList($limit = 10) {
		$list = M('gift_count')->field(['SUM(gold) as golds', 'to_uid'])->group("to_uid")->order('golds desc')->findPage($limit);
		if ($list['gtLastPage'] === true|!$list['data']) {
			return [];
		}
        $res = [];
        $userModel = model('open/User');
        foreach($list['data'] as $k=>$v){
            $res[$k]['user']['usid'] = $userModel->getUsidByUid($v['to_uid']);
            $res[$k]['user']['gold'] = (int)$v['golds'];
        }
		return $res;
	}
	/**
	 * @name 处理赠送礼物
	 * 必须有参数 gift_code 礼物编码
	 */
	public function do_haddle_give($order = []) {
		//检测礼物
        \think\Config::load(join(DIRECTORY_SEPARATOR, array(APP_PATH, 'api', 'config.php')));
        $config_list = model('admin/Config')->ApiServiceGetConf('gift');
        $this->exchange_list = array_column($config_list, 'gold', 'gift_code');
        
		$gift_gold = $this->exchange_list[$order['gift_code']];
		// if (!$gift_gold) {
		//	$this->error = '不明确的礼物类型';
		//	return false;
		// }
        $gift_name_list = array_column($config_list, 'name', 'gift_code');
		$num = (int) $order['count'] ?: 1;
		$count = (int) $gift_gold * $num;
		$desc = $gift_name_list[$order['gift_code']];
		if (!$gift_gold) {
			$log = [
				'num' => $count,
				'to_usid' => model('open/User')->getUsidByUid($order['to_uid']), //收款方
				'usid' => model('open/User')->getUsidByUid($order['uid']), //支出方
				'type' => 'gold',
                		'order' => date('YmdHi',NOW_TIME).mt_rand(100000,999999),
				'description' => $desc,
                		'order_type' => 'gift',
                		'ctime' => NOW_TIME
			];
           		M('gift_give_log')->add($log);
            		return true;
		}
		//转账
        $userModel = model('open/UserData');
        //数据同步
        $userModel->checkUserData($order['uid']);
        $userModel->checkUserData($order['to_uid']);
        //扣除服务器金币记录
		if (true === $this->goldDec($order['uid'], $count)) {
			//扣除支出方金币成功--添加收款方金币--优先添加 临时表的统计
			if (model('stream/Stream')->addInc('gold', $count, $order['to_uid']) || $this->goldInc($order['to_uid'], $count)) {
			    self::addGiftCount($order['uid'], $order['to_uid'], $count);
                $log = [
					'num' => $count,
					'to_usid' => model('open/User')->getUsidByUid($order['to_uid']), //收款方
					'usid' => model('open/User')->getUsidByUid($order['uid']), //支出方
					'type' => 'gold',
                    'order' => date('YmdHi',NOW_TIME).mt_rand(100000,999999),
					'description' => $desc,
                    'order_type' => 'gift',
                    'ctime' => NOW_TIME
				];
                M('gift_give_log')->add($log);
                $res = $userModel->checkUserPay($log);
                if($res !== true){
                    $this->error = $userModel->getError();
                }else{
                    //同步数据
                    //$userModel->checkUserData($order['uid'],true);
                    //$userModel->checkUserData($order['to_uid'],true);
                    return true;
                }
				
			}
            //返还金币
            if($this->goldInc($order['uid'], $count) && $log){
                M('gift_give_log')->where(['order'=>$log['order']])->delete();
            }
			$this->error = '赠送礼物失败';
			return false;
		} else {
			return false;
		}
        
	}
	/**
	 * @name 处理点赞
	 */
	public function do_haddle_zan($order = []) {
		$count = (int) $order['count'];
        $userModel = model('open/UserData');
        $userModel->checkUserData($order['to_uid']);
        $userModel->checkUserData($order['uid']);
		//给主播先加赞
		$tmp = model('stream/Stream')->addInc('zan_count', $count, $order['to_uid']);
		if ($tmp || false !== model('stream/Zan')->zanInc($order['to_uid'], $count)) {
			return true;
		} else {
			$tihs->error = '点赞失败';
			return false;
		}
	}
	/**
	 * @name 添加赠送礼物记录
	 */
	public function addGiftCount($uid = 0, $to_uid = 0, $count = 0) {
		if (!$uid || !$to_uid || !$count) {
			return 0;
		}

		//数据组装
		$data = [
			'uid' => $uid,
			'to_uid' => $to_uid,
		];
		$table = M('gift_count');
		if (!$table->where($data)->setInc('gold', $count)) {
			$data['gold'] = $count;
			return $table->add($data) ? true : false;
		}
		return true;
	}
}
